//
//  OnlineCommandTableViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/12/1.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "OnlineCommandTableViewController.h"
#import "TotalDeviceSelectedViewController.h"
#import "MsgCommand.h"
#import "UserModel.h"

#import <SVProgressHUD.h>

@interface OnlineCommandTableViewController ()<UITextFieldDelegate>

@property (strong , nonatomic) NSMutableDictionary * dataDictionary;
@property (strong, nonatomic) MsgCommand *msgCommand;
@property (strong, nonatomic) UserModel *userModel;

@end

static NSString * cellIdentifer = @"cell";

@implementation OnlineCommandTableViewController

-(MsgCommand *)msgCommand{
    
    if (!_msgCommand) {
        _msgCommand = [[MsgCommand alloc]init];
    }
    return _msgCommand;
    
}

-(NSMutableDictionary *)dataDictionary{
    
    if (!_dataDictionary) {
        
        NSString * path = [[NSBundle mainBundle] pathForResource:@"OnlineCommandCell" ofType:@"plist"];
        
        _dataDictionary = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
    }
    return _dataDictionary;
}

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"createtask"]  style:UIBarButtonItemStyleDone target:self action:@selector(toucTotalDeviceButton:)];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
//    self.tableView.alwaysBounceVertical = NO;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.dataDictionary.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSDictionary * dict = [self.dataDictionary objectForKey:[NSString stringWithFormat:@"%ld",(long)section]];
    
    NSArray * array = [dict objectForKey:@"data"];
    
    return array.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    NSDictionary * dict = [self.dataDictionary objectForKey:[NSString stringWithFormat:@"%ld",(long)section]];
    
    return [dict objectForKey:@"sectionName"];
    
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
        
    }
    
    NSDictionary * dict = [self.dataDictionary objectForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.section]];
    
    NSArray * array = [dict objectForKey:@"data"];
    
    [cell.textLabel setText:array[indexPath.row]];
    
    [cell.textLabel setTextColor:[UIColor grayColor]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    [self cellDidSelectedActionForCellName:cell.textLabel.text];
    
}

#pragma mark 点击事件
-(void)cellDidSelectedActionForCellName:(NSString *)cellName{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:cellName message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"CANCEL" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:cancelAction];
    
    
    
    if ([cellName isEqualToString:@"Current GPS Location"]) {
        
        [alertController setMessage:@"The current GPS location will be uploaded to website and app map."];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_CURRENT_GPS_LOCATION];
            
        }];
        
        [alertController addAction:okAction];
        
    }else if ([cellName isEqualToString:@"Current LBS Location"]){
        
        [alertController setMessage:@"The current GSM location will be uploaded to website and app map."];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_CURRENT_LBS_LOCATION];
            
        }];
        
        [alertController addAction:okAction];
        
    }else if ([cellName isEqualToString:@"Real Time Tracking"]){
        
        
        [alertController setMessage:@"Device will uploaded 6 GPS locations every minute for 1 hour.Repeat the command to prolong tracking time after 1 hour if needed.Routetrack is the highest power consumption tracking function.Battery will drained in couple hours with this function on."];
        
        UIAlertAction *onAction = [UIAlertAction actionWithTitle:@"ON" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_REAL_TIME_TRACKING_ON];
            
        }];
        
        UIAlertAction *offAction = [UIAlertAction actionWithTitle:@"OFF" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_REAL_TIME_TRACKING_OFF];
            
        }];
        
        
        
        [alertController addAction:onAction];
        [alertController addAction:offAction];
        
        
    }else if ([cellName isEqualToString:@"Check GPS Location"]){
        
        [alertController setMessage:@"Device will uploaded GPS location in appointed interval.Default as 1 GPS locationuploads every 6 hours.\n(5-1800 represents GPS data upload interval in minutes)"];
        
        __block UITextField *dataTextField;
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = @"5-1800 represents GPS data upload interval in minutes";
            
            textField.delegate = self;
            
            textField.keyboardType = UIKeyboardTypeNumberPad;
            
            dataTextField = textField;
            
        }];
        
        UIAlertAction *onAction = [UIAlertAction actionWithTitle:@"ON" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            if (dataTextField.text.length > 0) {
                
                NSString *commandString = [NSString stringWithFormat:@"%@%@*",MC_BODY_INTERVAL_TRACKING_CHECK_GPS_LOCATION_ON_WITHOUT_NUMBER,dataTextField.text];
                
                [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:commandString];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"Value can not empty."];
                
                [SVProgressHUD dismissWithDelay:1];
                
            }
            
            
            
        }];
        
        UIAlertAction *offAction = [UIAlertAction actionWithTitle:@"OFF" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_INTERVAL_TRACKING_CHECK_GPS_LOCATION_OFF];
            
        }];
        
        
        
        [alertController addAction:onAction];
        [alertController addAction:offAction];
        
    }else if ([cellName isEqualToString:@"Check LBS Location"]){
        
        
        [alertController setMessage:@"Device will uploaded GPS location in appointed interval.Default as 1 GPS locationuploads every 6 hours.\n(5-1800 represents GPS data upload interval in minutes)"];
        
        __block UITextField *dataTextField;
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = @"5-1800 represents GPS data upload interval in minutes";
            
            textField.delegate = self;
            
            textField.keyboardType = UIKeyboardTypeNumberPad;
            
            dataTextField = textField;
            
        }];
        
        UIAlertAction *onAction = [UIAlertAction actionWithTitle:@"ON" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            if (dataTextField.text.length > 0) {
                
                NSString *commandString = [NSString stringWithFormat:@"%@%@*",MC_BODY_INTERVAL_TRACKING_CHECK_LBS_LOCATION_ON_WITHOUT_NUMBER,dataTextField.text];
                
                [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:commandString];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"Value can not empty."];
                
                [SVProgressHUD dismissWithDelay:1];
                
            }
            
        }];
        
        UIAlertAction *offAction = [UIAlertAction actionWithTitle:@"OFF" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_INTERVAL_TRACKING_CHECK_LBS_LOCATION_OFF];
            
        }];
        
        
        
        [alertController addAction:onAction];
        [alertController addAction:offAction];
        
        
        
    }else if ([cellName isEqualToString:@"Motion Sleep"]){
        
        
        [alertController setMessage:@"Device will go to deep sleep mode and wake up when motion is detected.The phone function will be off during deep sleep, and no call or SMS can be replied until device wakes up."];
        
        UIAlertAction *onAction = [UIAlertAction actionWithTitle:@"ON" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_MOTION_SLEEP_ON];
            
        }];
        
        UIAlertAction *offAction = [UIAlertAction actionWithTitle:@"OFF" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_MOTION_SLEEP_OFF];
            
        }];
        
        
        
        [alertController addAction:onAction];
        [alertController addAction:offAction];
        
        
    }else if ([cellName isEqualToString:@"Status query"]){
        
        [alertController setMessage:@"Check system status"];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_STATUS_QUERY];
            
        }];
        
        [alertController addAction:okAction];
        
    }else if ([cellName isEqualToString:@"Device Information"]){
        
        [alertController setMessage:@"Software edition information and device’s serial number."];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_DEVICE_INFOMATION];
            
        }];
        
        [alertController addAction:okAction];
        
    }else if ([cellName isEqualToString:@"Reset"]){
        
        [alertController setMessage:@"Reset."];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.msgCommand getMessagePhoneNumberForSerialNumber:self.userModel.selectedDeviceSerialNumber Delegate:self title:nil body:MC_BODY_RESET];
            
        }];
        
        [alertController addAction:okAction];
        
    }
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark 只能输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


#pragma mark 点击列表按钮
-(void)toucTotalDeviceButton:(id)sender {
    
    TotalDeviceSelectedViewController *totalDeviceSelectedViewController = [[TotalDeviceSelectedViewController alloc]init];
    
    [self.navigationController showViewController:totalDeviceSelectedViewController sender:nil];
    
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
